<template>
  <div>
    <h3 class="title">{{ $t("host.title") }}</h3>
    <div class="search">
      <el-input
        class="input-with-select"
        :placeholder="$t('host.search.placeholder')"
        v-model="searchText"
      >
        <el-select
          v-model="select"
          slot="prepend"
          placeholder="criteria"
          style="width: 140px"
        >
          <el-option
            v-for="item in $t('host.options')"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>

        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
      <el-button type="primary" @click="searchHost">{{
        $t("host.search.searchBtn")
      }}</el-button>
      <el-button type="info" plain @click="resetSearch">{{
        $t("host.search.resetBtn")
      }}</el-button>
      <el-button
        type="success"
        plain
        icon="el-icon-circle-plus-outline"
        style="width: 300px"
        @click="createHost"
        >{{ $t("host.search.hostCreated") }}</el-button
      >
    </div>
    <el-table
      v-loading="loading"
      element-loading-text="Loading...."
      height="680px"
      ref="hostListRef"
      :data="hostList"
      :span-method="arraySpanMethod"
      :cell-style="cellStyle"
      style="width: 100%"
      :default-sort="{ prop: 'date', order: 'descending' }"
      border
    >
      <!-- <el-table-column type="selection" width="55"> </el-table-column> -->
      <el-table-column type="index" width="61" :label="$t('host.table.index')">
      </el-table-column>
      <el-table-column
        prop="name"
        :label="$t('host.table.name')"
        sortable
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column :label="$t('host.table.warningState')" width="60px">
        <template slot-scope="scope">
          <div
            v-show="scope.row.warningState"
            class="warningState"
            style="background-color: #f56c6c"
          ></div>
          <div
            v-show="!scope.row.warningState"
            class="warningState"
            style="background-color: #67c23a"
          ></div>
        </template>
      </el-table-column>
      <el-table-column prop="ip" label="IP" sortable width="130">
      </el-table-column>
      <!-- <el-table-column prop="cpu" label="CPU占有率" sortable> </el-table-column> -->
      <!-- <el-table-column prop="memory" label="内存"> </el-table-column> -->
      <!-- <el-table-column prop="wide_band" label="带宽"> </el-table-column> -->

      <el-table-column
        show-overflow-tooltip
        prop="due_date"
        :label="$t('host.table.due_date')"
      >
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="mac_address"
        :label="$t('host.table.mac_address')"
      >
      </el-table-column>

      <el-table-column
        show-overflow-tooltip
        prop="operating_system"
        :label="$t('host.table.operating_system')"
      >
      </el-table-column>
      <el-table-column prop="status" :label="$t('host.table.status')">
        <template slot-scope="{ row }">
          <div
            v-if="row.status == 0 ? true : false"
            class="square"
            style="background-color: #67c23a"
          ></div>
          <div
            v-if="row.status == 1 ? true : false"
            class="square"
            style="background-color: #f56c6c"
          ></div>
        </template>
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        :label="$t('host.table.username') + '/' + $t('host.table.password')"
      >
        <!-- <el-table-column prop="password" :label="$t('host.table.password')"> -->
        <template slot-scope="{ row }">
          <div class="user-pwd">
            <div>{{ row.username }}</div>
            <div class="hr"></div>
            <div>{{ row.password }}</div>
          </div>
        </template>
        <!-- </el-table-column> -->
      </el-table-column>

      <el-table-column label="shell" width="100px">
        <template slot-scope="{ row }">
          <el-button type="success" size="mini" plain @click="webshell(row)"
            >webshell</el-button
          >
          <!-- <el-button type="primary" size="mini" plain @click="shellDialog">{{
            $t("host.table.children.shell")
          }}</el-button>
          <el-button type="warning" size="mini" plain @click="resetShell">{{
            $t("host.table.children.clear")
          }}</el-button>
          <a href="ShellConfig://" style="display: none" ref="shellRef"></a> -->
        </template>
      </el-table-column>
      <el-table-column :label="$t('host.table.detail')" width="100px">
        <template slot-scope="scope">
          <el-button type="text" @click="detail(scope)">{{
            $t("host.table.children.detail")
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column :label="$t('host.table.option')" width="220px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="warning"
            icon="el-icon-edit"
            plain
            slot="reference"
            @click="editor(scope)"
            >{{ $t("host.message.edit") }}</el-button
          >
          <el-popconfirm
            :title="$t('host.message.delMsg')"
            @confirm="delHost(scope)"
            style="margin: 0 10px 0 10px"
          >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              plain
              slot="reference"
              >{{ $t("host.message.del") }}</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- <div class="hostFooter">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.page"
        :page-sizes="[5]"
        :page-size="queryInfo.pagesize"
        layout="total, prev, pager, next, jumper"
        :total="hostList.length"
      >
      </el-pagination>
    </div> -->
    <HostDetailDialog
      :detailDdialogVisible="detailDdialogVisible"
      :warningRuleList="warningRuleList"
      :hostDetail="hostDetail"
      @closeDialog="closeDialog"
      @selectChange="selectChange"
    ></HostDetailDialog>
    <HostCreatedDialog
      :hostCreatedDialogVisible="hostCreatedDialogVisible"
      :hostRow="hostRow"
      @closeDialog="closeHostCreatedDialog"
    ></HostCreatedDialog>
    <HostSSHDialog
      :hostSSHDialogVisible="hostSSHDialogVisible"
      @closeDialog="closeSSHDialog()"
    ></HostSSHDialog>
    <ShellDialog
      :shellDialogVisible="shellDialogVisible"
      @closeDialog="closeShellDialog"
    >
    </ShellDialog>
    <!-- <HostWebshell
      :webshellVisible="webshellVisible"
      :webshellRow="webshellRow"
      @closeDialog="closeWebshell"
    ></HostWebshell> -->
  </div>
</template>

<script>
import $ from "jquery";
import HostDetailDialog from "../../../components/HostDetailDialog.vue";
import HostCreatedDialog from "../../../components/HostCreatedDialog.vue";
import HostSSHDialog from "../../../components/HostSSHDialog.vue";
import ShellDialog from "../../../components/ShellDialog.vue";
// import HostWebshell from "../../../components/HostWebshell.vue";
export default {
  components: {
    HostDetailDialog,
    HostCreatedDialog,
    HostSSHDialog,
    ShellDialog,
  },
  activated() {
    this.getHostList();
  },
  mounted() {
    // this.getTableLabel();
  },
  created() {
    if (this.$route.query.hostName) {
      console.log(this.$route.query.hostName);
      this.searchText = this.$route.query.hostName;
      this.getSearchList(this.$route.query.hostName);
    } else {
      this.getHostList();
    }
  },
  updated: function () {
    // let str= "'C:\Program Files (x86)\NetSarang\Xshell 7\Xshell.exe'"
    // console.log(this.shellURL);
    $(".downloadButton").each(function () {
      var blob = new Blob(["自定义的内容"]);
      var url = URL.createObjectURL(blob);
      $(this).attr("href", url);
    });
  },
  data() {
    return {
      // loading 加载
      loading: false,
      hostId: 0,
      // 告警规则信息
      warningRuleList: null,
      hostRow: null,
      // shellURL: ["C:\Program Files (x86)\NetSarang\Xshell 7\Xshell.exe"],
      // 获取爬虫的参数对象
      queryInfo: {
        // 当前的页数
        page: 1,
        // 当前每页显示多少条数据
        pagesize: 10,
      },
      // 根据搜索字段名
      select: 1,
      // 搜索内容
      searchText: "",
      // 主机创建弹框显示隐藏
      hostCreatedDialogVisible: false,
      // 详情弹框是否显示
      detailDdialogVisible: false,
      // 主机SSH配置对话框显示与隐藏
      hostSSHDialogVisible: false,
      // 主机列表数据
      hostList: [],
      hostDetail: {},
      shellDialogVisible: false,
      isShellFirst: true,
    };
  },
  methods: {
    webshell(row) {
      let routeData = this.$router.resolve({
        path: "/Webshell",
        query: { ip: row.ip, username: row.username, password: row.password },
      });
      window.open(routeData.href, "_blank");
    },
    closeWebshell() {
      this.webshellVisible = false;
    },
    // 重新配置shell路径
    resetShell() {
      window.localStorage.removeItem("Xshell_URL");
      if (!window.localStorage.getItem("Xshell_URL")) {
        this.$message.info(this.$t("host.message.resetURL"));
      }
    },
    // 打开shell编辑对话框
    shellDialog() {
      let url = window.localStorage.getItem("Xshell_URL");
      if (!url) {
        // 如果shell未配置路径的话 先配置路径
        this.shellDialogVisible = true;
      } else {
        // 如果shell已经配置了路径 直接打开
        this.$refs.shellRef.click();
      }
    },
    // 关闭shell编辑对话框
    closeShellDialog() {
      this.shellDialogVisible = false;
    },
    // 分页功能
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },
    // 获取table表头
    // getTableLabel() {
    //   this.options = [
    //     { id: 1, name: "主机名" },
    //     { id: 2, name: "IP" },
    //     { id: 3, name: "服务截止时间" },
    //     { id: 4, name: "操作系统" },
    //     { id: 5, name: "系统用户" },
    //   ];
    // },
    // 合并行或列
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      // console.log(row, column, rowIndex, columnIndex);
      // if (rowIndex % 2 === 0 && columnIndex !== 8) {
      //   return [2, 1];
      // }
    },
    // 指定某一个单元格的特定样式
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 8) {
        return {
          padding: "0px",
          // backgroundColor: "red",
        };
      }
    },
    // 获取主机列表信息
    async getHostList() {
      this.loading = true;
      const { data: res } = await this.$http.get("/host");
      this.hostList = res;
      this.loading = false;
      console.log("------------主机列表数据-----------", res);
    },
    // 创建主机函数
    createHost() {
      this.hostRow = null;
      this.hostCreatedDialogVisible = true;
    },
    // 编辑主机
    editor({ row }) {
      console.log(row);
      this.hostRow = row;
      this.hostCreatedDialogVisible = true;
    },
    // 删除主机函数
    async delHost(scope) {
      const { data: res } = await this.$http.get("/host/del", {
        params: { client_id: scope.row.id },
      });
      console.log(res);
      if (res.code != 0)
        return this.$message.error(this.$t("host.message.error"));
      this.$message.success(this.$t("host.message.success"));
      this.getHostList();
    },
    selectChange(val) {
      console.log(val);
    },
    // 详情弹框函数
    detail(scope) {
      // 获取告警规则信息
      this.$http.get("/business/warning/rule/list").then((res) => {
        console.log(res.data.data);
        this.warningRuleList = res.data.data;
      });
      // this.hostId = scope.row.id;
      // this.detailDdialogVisible = true;

      this.$http
        .get("/host/info", {
          params: { client_id: scope.row.id },
        })
        .then((res) => {
          // 先赋值  再打开对话框 这样才更好的在对话框里面获取到数据
          this.hostDetail = res.data;
          console.log("=======hostDetail===========", res.data);
          this.detailDdialogVisible = true;
        })
        .catch((err) => {
          this.$message.error("获取主机详情失败");
        });
    },
    // 主机SSH配置对话框
    shellConfig() {
      // this.hostSSHDialogVisible = true;
      // this.$router.push("");
    },
    // 主机SSH配置对话框关闭
    closeSSHDialog() {
      this.hostSSHDialogVisible = false;
    },
    // 搜索功能
    searchHost() {
      let str = this.searchText.replace(/\s*/g, "");
      console.log(this.select);
      this.getSearchList(str);
    },
    // 请求搜索接口
    async getSearchList(searchText) {
      const { data: res } = await this.$http.get("/host/query", {
        params: { query_text: searchText, query_type: this.select },
      });
      this.hostList = res;
    },

    // 重置搜索输入框
    resetSearch() {
      this.searchText = "";
      this.select = 1;
      this.getHostList();
    },
    // 关闭详情弹框
    closeDialog() {
      this.detailDdialogVisible = false;
    },
    closeHostCreatedDialog(v) {
      this.hostCreatedDialogVisible = false;
      if (v === undefined) {
        this.getHostList();
      }
    },
  },
};
</script>

<style lang="less" scoped>
.title {
  color: #606266;
}
.search {
  margin: 10px 0;
  .el-input {
    width: 34%;
  }
  .el-button {
    margin-left: 10px;
  }
}
.el-table {
  // background-color: pink !important;
  .hostName {
    display: inline-block;
    width: 80%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .editBtn {
    float: right;
    // height: 25px;
    padding: 4px;
  }
  .warningState {
    margin: 3px 0;
    width: 15px;
    height: 15px;
    border-radius: 50%;
  }
  .square {
    margin: 3px 0;
    width: 15px;
    height: 15px;
    border-radius: 50%;
  }
  .user-pwd {
    width: 100%;
    height: 62px;
    // background-color: pink;
    div:nth-child(odd) {
      width: 100%;
      height: 31px;
      line-height: 31px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .hr {
      position: absolute;
      left: 0;
      width: 100%;
      height: 1px;
      background-color: #ebeef5;
    }
  }
}
.hostFooter {
  margin-top: 10px;
}
.downloadButton {
  text-decoration: none;
  color: #409eff;
}
</style>